package com.taptech.doufu.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.taptech.doufu.R;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.constant.TagType;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.bean.HomeTopBean;
import com.taptech.doufu.bean.TagModel;
import com.taptech.doufu.presenter.home.TagGovernmentPresenter;
import com.taptech.doufu.services.NovelCreateServices;
import com.taptech.doufu.ui.activity.base.DiaobaoBaseActivity;
import com.taptech.doufu.util.TMAnalysis;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.ui.view.TagSelectView;
import com.taptech.doufu.ui.view.WaitDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

public class TagSelectActivity extends DiaobaoBaseActivity implements TagGovernmentPresenter.OnTagView,TagSelectView.OnSelectTag {


    public static String INTENT_KEY_CUSTOM_TAG = "CUSTOM_TAG";
    public static String INTENT_KEY_GOVERMENT_TAG = "GOVERMENT_TAG";
    public static String INTENT_KEY_SEXUALITY = "SEXUALITY_FLAG";
    public static String INTENT_KEY_TOPIC_ID = "TOPIC_ID_FLAG";
    public static String INTENT_KEY_ALL_TAGS = "ALL_TAGS";

    private TagGovernmentPresenter presenter;
    private TextView tvMakeSure;
    private LinearLayout llContent;
    private HashMap<Integer, String> map = new HashMap<>();
    private ArrayList<String> customTags = new ArrayList<>();
    private int sexuality;
    private String checkFillMsg,checkRepeatMsg;

    private String topicId = "";

    private WaitDialog waitDialog;

    public String getSelectThemeKey(){
        String key = "";
        if (map != null && map.containsKey(TagType.TYPE_THEME)) {
            key = map.get(TagType.TYPE_THEME);
        }
        return key;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tag_select);
        map = (HashMap<Integer, String>) getIntent().getSerializableExtra(INTENT_KEY_GOVERMENT_TAG);
        customTags = getIntent().getStringArrayListExtra(INTENT_KEY_CUSTOM_TAG);
        sexuality = getIntent().getIntExtra(INTENT_KEY_SEXUALITY, 1);
        topicId = getIntent().getStringExtra(INTENT_KEY_TOPIC_ID);
        init();
        loadData();
        waitDialog = new WaitDialog(TagSelectActivity.this, R.style.updateDialog, "正在上传...");
    }

    private void loadData() {
        presenter.getGovernmentTag(this,sexuality,topicId);
    }

    private void init() {
        presenter = new TagGovernmentPresenter(this);
        llContent = (LinearLayout) findViewById(R.id.llContent);
        tvMakeSure = (TextView) findViewById(R.id.tvMakeSure);
        tvMakeSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isCanUpload()) {
                    if (isTagContentNomal()) {
                        if (!TextUtils.isEmpty(topicId)) {
                            uploadTags();
                        }else{
                            Intent intent = new Intent();
                            intent.putExtra(INTENT_KEY_CUSTOM_TAG, customTags);
                            intent.putExtra(INTENT_KEY_GOVERMENT_TAG, map);
                            setResult(RESULT_OK,intent);
                            finish();
                        }
                    }else {
                        TMAnalysis.event(TagSelectActivity.this, "tag_edit_page_check_repeat");
                        Toast.makeText(TagSelectActivity.this,checkRepeatMsg,Toast.LENGTH_LONG).show();
                    }
                }else {
                    TMAnalysis.event(TagSelectActivity.this, "tag_edit_page_check_fill");
                    Toast.makeText(TagSelectActivity.this,checkFillMsg,Toast.LENGTH_LONG).show();
                }
            }
        });
    }


    private void uploadTags() {
        waitDialog.show();
        //直接上传
        NovelCreateServices.getInstance().saveTopicNovel(new HttpResponseListener() {
            @Override
            public void handleResponse(int handleType, HttpResponseObject response) {
                if (waitDialog != null && waitDialog.isShowing()) {
                    waitDialog.dismiss();
                }
                if (response.getStatus() == Constant.STATUS_SUCCESS){
                    UIUtil.toastMessage(TagSelectActivity.this, "修改成功");
                    Intent intent = new Intent();
                    intent.putExtra(INTENT_KEY_CUSTOM_TAG, customTags);
                    intent.putExtra(INTENT_KEY_GOVERMENT_TAG, map);
                    HomeTopBean bean = new HomeTopBean();
                    bean.setJson2((JSONObject) response.getData());
                    if (bean.getTags() != null) {
                        intent.putExtra(INTENT_KEY_ALL_TAGS,bean.getTags());
                    }
                    setResult(NovelCreateSetActivity.NOVEL_TAGS_RESULT, intent);
                    finish();
                }else{
                    UIUtil.toastMessage(TagSelectActivity.this, "修改失败，请重试");
                }
            }
        }, topicId, null, null, null, TagGovernmentPresenter.getAllTagList(customTags,map), null, null);

    }


    /**
     * 判断标签选择是否正常
     * @return
     */
    private boolean isTagContentNomal() {
        for (String tag:customTags) {
            if (map.containsValue(tag)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onResult(TagModel model) {
        checkFillMsg = model.getCheck_fill_msg();
        checkRepeatMsg = model.getCheck_repeat_msg();
        if (model.getList() != null) {
            updateUI(model.getList());
        }
    }

    private void updateUI(List<TagModel.TagBean> list) {
        for (TagModel.TagBean bean:list) {
            String selectTag = map.get(bean.getType());
            String selectChildTag = "";
            if (!bean.isCustom() && !map.containsKey(bean.getType())) {
                map.put(bean.getType(),"");
            }
            if (!bean.isCCustom() && !TextUtils.isEmpty(bean.getcTitle())) {
                if (!map.containsKey(bean.getcType())){
                    map.put(bean.getcType(), "");
                }
                selectChildTag = map.get(bean.getcType());
            }

            TagSelectView view = new TagSelectView(this,bean,this,selectTag,selectChildTag,customTags);
            llContent.addView(view);
        }
    }


    private boolean isCanUpload() {
        Collection<String> values = map.values();
        for (String value:values) {
            if (TextUtils.isEmpty(value)) {
                return false;
            }
        }
        return true;
    }

    @Override
    public void onError() {

    }

    @Override
    public void onChange(int type, String tag) {
        map.put(type, tag);
    }



    @Override
    public void onChangeCustomTag(ArrayList<String> list) {
        customTags = list;
    }

    @Override
    public void jumpToCustomTag(ArrayList<String> list) {
        //跳转到自定义页面
        Intent intent = new Intent(this, AddTagTosActivity.class);
        intent.putExtra("existTagsList", list);
        intent.putExtra("TYPE_FROM", Constant.OBJECT_TYPE_NOVEL);
        intent.putExtra(AddTagTosActivity.INTENT_KEY_SEXUALITY, sexuality);
        intent.putExtra(AddTagTosActivity.INTENT_KEY_THEME_KEY, getSelectThemeKey());
        startActivity(intent);
    }
}
